package br.ufes.inf.lprm.cwtools.web;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AndroidApplication extends HttpServlet {
    private static final long serialVersionUID = 1L;

    //XMLs de configuração do GW-Arquigrafia
    private static final String GWDefaultConfigurationXML = "../GW-Application-Arquigrafia/WEB-INF/groupware-workbench/collablet-deployment/environment/Default/CollabletDescriptor.xml";
    private static final String GWBinomialConfigurationXML = "../GW-Application-Arquigrafia/WEB-INF/groupware-workbench/collabElement-deployment/br.org.groupwareworkbench.collablet.coop.Binomial/CollabletDescriptor.xml";
    //XMLs de configuração do GW-AndroidApplication
    private static final String GWAndroidConfigurationXML = "/WEB-INF/AndroidApplication.xml";
    
    //Constantes de conexão com o banco de dados
    private static final String dbDriver = "com.mysql.jdbc.Driver";
    private static final String dbConnection = "jdbc:mysql://localhost:3306/groupware_workbench_arquigrafia";
    private static final String dbUsername = "groupwareUser";
    private static final String dbPassword = "102938";
    
    //Queries SQL para buscar os dados do banco
    private static final String GWSQLComponents = "SELECT componentIdInstance, componentCod FROM GCFF_ComponentInstance WHERE enabled = 1 ORDER BY componentIdInstance DESC LIMIT 12;";
    
    //URLs do GW-Arquigrafia
    private static final String GWLoginPostUrl = "/groupware-workbench/#collabletId/userMgr/#collabElementId/login";
    private static final String GWBinomiosPostUrl = "/groupware-workbench/#collabletId/photo/show/#entityId";
    private static final String GWImageUploaderPostUrl = "/groupware-workbench/#collabletId/photo/registra";
    //private static final String GWImageSearchDefaultUrl = "";
    private static final String GWImageSearchSearchUrl = "/groupware-workbench/#collabletId/photo/buscaA"; //POST: nome=<valor>&descricao=<valor>&lugar=<valor>&date=<valor>

    private String getDeployedPath(String relativePath){
    	File file = new File(getServletContext().getRealPath("/"));
    	
    	if (relativePath.substring(0, 3).equals("../")){
    		file = file.getParentFile();
    		relativePath = relativePath.substring(3);
    	}else if(relativePath.charAt(0) == '/'){
    		relativePath = relativePath.substring(1);
    	}
    	return file.getAbsolutePath() + "/" + relativePath;
    }
    
    private String getFileContents(String fullPath){
    	if(fullPath == null){ return ""; }
    	
    	File file = new File(fullPath);
    	
    	byte[] bytes = new byte[(int) file.length()];
    	try {
    		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
			bis.read(bytes);
			bis.close();
		} catch (IOException e) {
			return null;
		}
    	
    	return new String(bytes);
    }

    public void doGet(HttpServletRequest req, HttpServletResponse resp)
    		throws ServletException, IOException {
        
        int collabletDefault = 0;
        int collabElementUser = 0;
        int collabletPhoto = 0;
        int collabElementBinomial = 0;
        String strBinomiosPorExtenso;
        PrintWriter out = resp.getWriter();
   
        try{
        	//Verifica se está usando o GW-Android
	        Map<String, String> lsAttr = AndroidConfigurationParser.parse(new FileInputStream(getDeployedPath(GWDefaultConfigurationXML)));
	        try{
	        	if(!(lsAttr.get("useGWAndroidClient").equalsIgnoreCase("true"))){
	        		throw new Exception();
	        	}
	        }catch(Exception e){
        		resp.sendError(404);
	        	return;
	        }
	        
	        lsAttr = AndroidConfigurationParser.parse(new FileInputStream(getDeployedPath(GWBinomialConfigurationXML)));
	        strBinomiosPorExtenso = lsAttr.get("br.ufes.cwtools.android.components.Binomios.string_binomios");
	        
	        if(strBinomiosPorExtenso == null){
	        	out.println("ERRO! Não achou os binômios.");
            	return;
	        }
        }catch(Exception e){
            resp.getWriter().println(e.getMessage());
            e.printStackTrace(resp.getWriter());
            return;
        }
        
        try {
            //Conecta ao banco
            Class.forName(dbDriver);
            Connection db = DriverManager.getConnection(dbConnection, dbUsername, dbPassword);
            PreparedStatement stmt = db.prepareStatement(GWSQLComponents);
            ResultSet rs = stmt.executeQuery();
            
            //Busca o Id dos componentes
            while(rs.next()){
                String strCollab = rs.getString("componentCod");
                int collabId = rs.getInt("componentIdInstance");
//                |                   1 | environment/Default                                           |
//                |                   2 | br.org.groupwareworkbench.collablet.coord.User                |
//                |                   3 | br.org.groupwareworkbench.collablet.communic.Tag              |
//                |                   4 | br.org.groupwareworkbench.collablet.coord.Role                |
//                |                   5 | br.org.groupwareworkbench.collablet.coop.Binomial             |
//                |                   6 | br.org.groupwareworkbench.collablet.coop.Recommend            |
//                |                   7 | br.org.groupwareworkbench.collablet.communic.Comment          |
//                |                   8 | br.org.groupwareworkbench.collablet.communic.GoogleMapsMarker |
//                |                   9 | cooperation-collablets/Photo                                  |
//                |                  10 | br.org.groupwareworkbench.collablet.coop.Binomial             |
//                |                  11 | br.org.groupwareworkbench.collablet.coop.Recommend            |
//                |                  12 | br.org.groupwareworkbench.collablet.communic.Comment
                if("environment/Default".equalsIgnoreCase(strCollab)){
                    collabletDefault = collabId;
                }else if("br.org.groupwareworkbench.collablet.coord.User".equalsIgnoreCase(strCollab)){
                    collabElementUser = collabId;
                //FIXME: O id da instância dos binômios só está funcionando porque o ativo é o segundo registro, e o segundo sobrescreve o valor do primeiro
                }else if("br.org.groupwareworkbench.collablet.coop.Binomial".equalsIgnoreCase(strCollab)){
                    collabElementBinomial = collabId;
                }else if("cooperation-collablets/Photo".equalsIgnoreCase(strCollab)){
                    collabletPhoto = collabId;
                }
            }
            
            //Fecha a conexão, liberando os recursos
            rs.close();
            stmt.close();
            db.close();
        } catch (Exception e) {
            resp.getWriter().println(e.getMessage());
            e.printStackTrace(resp.getWriter());
        	return;
        }
        
        if(collabletDefault == 0 || collabElementUser == 0 || collabletPhoto == 0 || collabElementBinomial == 0){
        	resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println("Parâmetros incompletos. Não foi possível buscar os valores no Banco de Dados.");
            return;
        }
        
        //Busca o XML de referência
        try{
        	String xml = getFileContents(getDeployedPath(GWAndroidConfigurationXML));
	        String tmp;
	        
	        xml = xml.replaceAll("#BinomiosNamePairsAndIds", strBinomiosPorExtenso);

	        tmp = GWLoginPostUrl.replaceAll("#collabletId", String.valueOf(collabletDefault));
	        tmp = tmp.replaceAll("#collabElementId", String.valueOf(collabElementUser));
	        xml = xml.replaceAll("#LoginPostUrl", tmp);

	        tmp = GWImageUploaderPostUrl.replaceAll("#collabletId", String.valueOf(collabletPhoto));
	        xml = xml.replaceAll("#ImageUploaderPostUrl", tmp);
	     
	        tmp = GWBinomiosPostUrl.replaceAll("#collabletId", String.valueOf(collabletPhoto));
	        xml = xml.replaceAll("#BinomiosPostUrl", tmp);
	        
	        tmp = GWImageSearchSearchUrl.replaceAll("#collabletId", String.valueOf(collabletPhoto));
	        xml = xml.replaceAll("#ImageSearchSearchUrl", tmp);

	        resp.setContentType("text/xml");
	        resp.setCharacterEncoding("UTF-8");
	        resp.getWriter().print(xml);

        }catch(Exception e){
            resp.getWriter().println(e.getMessage());
            e.printStackTrace(resp.getWriter());
            return;
        }
    }
}
